#
# Makefile for KM texture utils
#
#VPATH = src

GA_BASE = galib247

INCLUDE = -Iinclude -I$(GA_BASE)

CPPFLAGS = -DDEBUG_LEVEL=0
CFLAGS_BASE = -Wall -Wno-unused -g $(INCLUDE)
# Temporarily reduce the optimization level if necessary for debugging
CFLAGS = $(CFLAGS_BASE) -O3
CC = gcc

# default
#LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)

CXX = g++
CXXFLAGS = $(CFLAGS)

LDFLAGS = -lm $(GA_BASE)/ga/libga.a

sources = $(wildcard src/*.cpp) $(wildcard src/strategies/*.cpp)

###########
# Only perform this part if compiling the gui
ifeq ($(findstring testgui,$(MAKECMDGOALS)),testgui)

QT_INCLUDE_BASE = /usr/include/qt4
QT_INCLUDE = -I/usr/share/qt4/mkspecs/linux-g++ -I$(QT_INCLUDE_BASE) -I$(QT_INCLUDE_BASE)/QtCore -I$(QT_INCLUDE_BASE)/QtGui  -I/usr/X11R6/include
#Uncomment this to turn off debug output from Qt
#QT_NO_DEBUG =  -DQT_NO_DEBUG
QT_DEFINES = -DQT_GUI_LIB -DQT_CORE_LIB $(QT_NO_DEBUG)
QT_LIBS = -lQtOpenGL -lQtGui -lQtCore
MOC = moc-qt4

INCLUDE += $(QT_INCLUDE)
CPPFLAGS += $(QT_DEFINES)
LDFLAGS += $(QT_LIBS)

gui_sources = $(wildcard src/gui/*.cpp)
moc_sources = $(patsubst include/gui/%.h, src/gui/moc/moc_%.cpp, $(wildcard include/gui/*.h))
gui_sources_with_moc = $(gui_sources) $(moc_sources)

endif
###########

.PHONY: all
all: test

# The following rule is intended to help make rebuild the project properly,
# even if we only changed a header file.
# Explanation of the rule (which I copied from an example!):
#   prepare to exit if any command fails; remove %.d
#   generate prereq info with "g++ -MM", and store in %.d.tmp-M
#   transform "%.o: " into "%.o %.d : ", and store in %.d
#   remove %.d.tmp-M
%.d: %.cpp
	@set -e; echo making $@ from $<; rm -f  $@; \
#  echo $(CXX) $(INCLUDE) -MM $(CPPFLAGS) $< \> $@.tmp-M; \
  $(CXX) $(INCLUDE) -MM $(CPPFLAGS) $< > $@.tmp-M; \
#  echo sed \'s,\($(*F)\)\.o[ :]*,\1.o $@ : ,g\' \< $@.tmp-M \> $@; \
  sed 's,\($(*F)\)\.o[ :]*,$(*D)/\1.o $@ : ,g' < $@.tmp-M > $@; \
  rm -f $@.tmp-M

#%.rcc: %.qrc
#	rcc -binary $< -o $@

src/gui/moc/moc_%.o: src/gui/moc/moc_%.cpp

src/gui/moc/moc_%.cpp: include/gui/%.h
	$(MOC) $(QT_DEFINES) $(INCLUDE) $< -o $@

# Don't include the .d files if the target is "clean"
ifneq ($(MAKECMDGOALS),clean)
-include $(sources:.cpp=.d) TestMain.d
ifeq ($(findstring testgui,$(MAKECMDGOALS)),testgui)
-include $(gui_sources:.cpp=.d) TestGUIMain.d
endif
endif

test: $(sources:.cpp=.o) TestMain.o
	$(LINK.cpp) $^ -o $@ $(LDFLAGS)

testgui_targets = $(sources:.cpp=.o) $(gui_sources_with_moc:.cpp=.o) resource/qrc_deck.o TestGUIMain.o
testgui: $(testgui_targets)
	$(LINK.cpp) $(testgui_targets) -o $@ $(LDFLAGS)

resource/qrc_deck.cpp:
	rcc resource/deck.qrc > $@

.PHONY: clean
clean:
	rm -f test testgui Test*.o Test*.d; \
  cd resource && rm -f *.o && \
  cd ../src && rm -f *.o *.d && \
  cd strategies && rm -f *.o *.d && \
  cd ../gui && rm -f *.o *.d && \
  cd moc && rm -f *

.PHONY: dummy
dummy:
	echo $(sources)